import React, { useRef } from 'react';
import { Button, Tag, Tooltip, Modal, message } from 'antd';
import { DownOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { request, Access, useAccess } from 'umi';
import { api } from '@/global';
import dayjs from 'dayjs';
import PDFRender from '@/components/PDFRender';
import DOCXRender from '@/components/DOCXRender';
import Field from '@ant-design/pro-field';
import FileUpload from '../FileUpload';
const confirm = Modal.confirm;

type FileListType = {
  id: string;
  fileName: string;
  fileSuffix: string;
  createTime: string;
  fileDescribe: string;
  fileOssPath: string;
  fileType: string;
  fileStorageName: string;
  fileDownload: number;
};

const downloadFile = (data, fileName) => {
  if (!data) {
    return;
  }
  const url = window.URL.createObjectURL(new Blob([data]));
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', fileName + '.pdf');
  document.body.appendChild(link);
  link.click();
};

export default () => {
  const actionRef = useRef<ActionType>();
  const access = useAccess();

  const deletFile = async (id: string) => {
    const result = await request(api.deleteFile, {
      method: 'POST',
      data: {
        id,
      },
    });

    if (result.success) {
      message.info('删除成功');
      actionRef.current?.reload();
    }
  };
  const columns: ProColumns<FileListType>[] = [
    {
      dataIndex: 'id',
      valueType: 'indexBorder',
    },
    {
      title: '文件名称',

      dataIndex: 'fileName',
    },
    {
      title: '文件后缀',
      dataIndex: 'fileSuffix',
    },
    {
      title: '文件类型',

      dataIndex: 'fileType',
      render: (_, b) => {
        if (b.fileType == '1') {
          return (
            <Tag key={b.id} color={'#13c2c2'}>
              线上文件
            </Tag>
          );
        } else if (b.fileType == '2') {
          return (
            <Tag key={b.id} color={'#fa8c16'}>
              线下文件
            </Tag>
          );
        } else if (b.fileType == '3') {
          return (
            <Tag key={b.id} color={'#ecd452'}>
              审批文件
            </Tag>
          );
        }
      },
    },
    {
      title: '所属存储室',

      dataIndex: 'fileStorageName',
    },
    {
      title: '文件图示',
      render: (_, b) => {
        if (b.fileType == '2') {
          return (
            <Field key={b.id} text={b.fileOssPath} valueType="image" mode={'read'} plain={false} />
          );
        } else {
          return <div />;
        }
      },
    },
    {
      title: '创建时间',
      width: 140,
      key: 'since',
      dataIndex: 'createTime',
      valueType: 'date',
      sorter: (a: FileListType, b: FileListType) => {
        const acreate = dayjs(a.createTime).valueOf();
        const bcreate = dayjs(b.createTime).valueOf();
        return acreate - bcreate;
      },
    },
    {
      title: '下载次数',
      dataIndex: 'fileDownload',
      sorter: (a: FileListType, b: FileListType) => {
        return a.fileDownload - b.fileDownload;
      },
    },
    {
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      render: (_, b) => [
        b.fileSuffix === 'pdf' && (
          <Access key={b.id} accessible={access.normalButtonFilter('FILE:VIEW')}>
            <PDFRender key={b.fileOssPath} url={b.fileOssPath} title="预览" />
          </Access>
        ),
        b.fileSuffix === 'docx' && (
          <Access key={b.id} accessible={access.normalButtonFilter('FILE:VIEW')}>
            <DOCXRender key={b.fileOssPath} url={b.fileOssPath} title="预览" />
          </Access>
        ),
        (b.fileSuffix === 'png' || b.fileSuffix === 'jpg' || b.fileSuffix === 'jpeg') && (
          <Access key={b.id} accessible={access.normalButtonFilter('FILE:VIEW')}>
            <Field text={b.fileOssPath} valueType="image" mode={'read'} plain={false} />
          </Access>
        ),
        <Access key={b.id} accessible={access.normalButtonFilter('FILE:DOWNLOAD')}>
          <a
            key={b.fileOssPath + 'download'}
            onClick={() => {
              request(api.addFileDownload, {
                params: {
                  id: b.id,
                },
              });

              if (b.fileSuffix === 'pdf') {
                downloadFile(b.fileOssPath, b.fileName);
              } else {
                window.open(b.fileOssPath);
              }
            }}
          >
            下载
          </a>
        </Access>,
        <Access key={b.id} accessible={access.normalButtonFilter('PRIVATE_FILE:DELETE')}>
          <a
            key="link3"
            onClick={() => {
              confirm({
                title: '确定是否删除' + b.fileName,

                okText: '删除',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                  console.log(b.id);

                  deletFile(b.id);
                  actionRef.current?.reload();
                },
                onCancel() {
                  message.info('已经取消');
                },
              });
            }}
          >
            删除
          </a>
        </Access>,
        ,
      ],
    },
  ];

  const reload = () => {
    actionRef.current?.reload();
  };

  return (
    <ProTable<FileListType>
      actionRef={actionRef}
      columns={columns}
      tooltip="为什么这里不能上传存储文件？因为存储室的文件由存储室的负责人进行整理，教师和学生负责接受结果.这里上传的文件会上传到你的私人文件夹下进行保存"
      request={async (params, sorter, filter) => {
        const result = await request(api.getPrivateFileList);

        return result;
      }}
      rowKey="id"
      pagination={{
        showQuickJumper: true,
      }}
      search={false}
      dateFormatter="string"
      headerTitle="文件列表"
      toolBarRender={() => [<FileUpload key="upload" reload={reload} />]}
    />
  );
};
